import { Box } from "@mui/material";
import OperatorIO from "../OperatorIO";
import ErrorView from "../../../core/src/plugins/SchemaIO/components/ErrorView";
import { stringifyError } from "../utils";

export default function OperatorPromptOutput({ operatorPrompt, outputFields }) {
  const executorError = operatorPrompt?.executorError;
  const resolveError = operatorPrompt?.resolveError;
  const error = resolveError || executorError;

  if (!outputFields && !executorError && !resolveError) return null;

  const { result } = operatorPrompt.executor;
  const defaultMsg = "Error occurred during operator execution";
  const message = error?.bodyResponse?.error;
  const reason = message ? defaultMsg + ". " + message : defaultMsg;

  return (
    <Box p={2}>
      {outputFields && (
        <OperatorIO
          id={operatorPrompt.id}
          type="output"
          data={result}
          schema={operatorPrompt.outputFields}
        />
      )}
      {error && (
        <ErrorView
          schema={{ view: { detailed: true } }}
          data={[
            {
              reason,
              details: stringifyError(error),
            },
          ]}
        />
      )}
    </Box>
  );
}
